<template>
  <div id="samstoSpecboxList">
    <div class="bodyContent">
      <div class='area'>
        <vxe-toolbar class-name="bg-grey light">
          <template #buttons>
            <!-- <vxe-input v-model="form.keyvalue" type="search" clearable class="vxeInputSearch margin-left-xs" placeholder="关键字查询" @keyup.enter.native="findList" @search-click="findList" @clear="findList"></vxe-input> -->
            <vxe-button type="text" class="button-blue" content="选择标本盒" @click="changeBoxOrder"></vxe-button>
            <vxe-button type="text" class="button-blue" content="确认入库" @click="askBoxOrder"></vxe-button>
          </template>
        </vxe-toolbar>
        <div class="tableBox">
          <div class="sample-box">
            <div class="rack">
              <div v-for="row in boxData.lData" :key="'row-' + row" class="rack-row">
                <div v-for="col in boxData.wData" :key="'col-' + col" class="rack-cell" :class="[getCellClass(row, col),getIsActived(row, col)?'selected':'']" @click="selectCell(row, col)">
                  <span class="cell-label">{{ row }}{{ col }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <el-drawer v-model="drawer" title="架层信息">
        <SamstoSpecboxForm ref="samstoSpecboxFormRef" :currentRow="curSelectRow" @findList="findList" />
      </el-drawer>
    </div>
    <vxe-modal :title="`留样盒信息`" width="90vw" height="88vh" v-model="dialogFormVisible" draggable show-footer mask-closable :mask="false">
      <template #title>
        <span class="margin-right">请选择留样盒</span>
      </template>
      <template #default>
        <StoragedisplayV1 ref="storagedisplayRef" :isBreadcrumb="false" @changeBox="changeBox"/>
      </template>
      <template #footer>
        <div class="flex justify-end">
          <el-button type="primary" v-loading="showLoading" @click="dialogFormVisible=false">确定</el-button>
        </div>
      </template>
    </vxe-modal>
  </div>
</template>

<script lang="ts" setup>
// 引入组件区 ==========
import { reactive, ref, getCurrentInstance, onMounted, watch, PropType } from 'vue';
import type { VxeTableInstance } from 'vxe-table';
import { AppStore } from '@/stores/store';
import SamstoSpecboxForm from "../form/SamstoSpecboxForm.vue";
import {IsEmpty, getAssetsFile, formatDateTime} from '@/utils/common';
import { samstoSpecboxFindInfoByCode } from '@/views/lab_sys/samsto_set/apis/samsto_api';
import { isEmpty } from 'xe-utils';
import { forEach } from 'lodash';
import StoragedisplayV1 from '@/views/lab_sys/samsto_set/StoragedisplayV1.vue';
import {VxeMessage, VxeNotifyType} from "@/utils/CommonMessage";
let store = AppStore();

// 全局变量定义区 ==========
let { proxy }: any = getCurrentInstance();
let dialogFormVisible = ref(false);
// 左侧表格:
let showLoading = ref(false); //刷新+表格加载
const form = reactive({ keyvalue: '' }); //根据关键字查询
const tableRef = ref<VxeTableInstance<RowVO>>(); //表格ref标记
const tableData = reactive<Map<String, SpecboxOrder>[]>([]); //表格数据
const selectStartItem = ref({}); //表格数据
const tableHard = ref([
  { title: "#", field: "#" },
  { title: "A", field: "A" },
  { title: "B", field: "B" },
  { title: "C", field: "C" },
  { title: "D", field: "D" },
  { title: "E", field: "E" },
  { title: "F", field: "F" },
  { title: "G", field: "G" },
  { title: "G", field: "G" },
  { title: "H", field: "I" },
]); //表头
const orderNumberArr = reactive([]);
const specboxOrderList = reactive([]);
const curSelectRow = ref({});
const info = ref({});
let storagedisplayRef = ref(null);
let tableHeight = ref(window.innerHeight - 200);
const drawer = ref(false)
// 右侧表单:
const samstoSpecboxFormRef = ref<InstanceType<typeof SamstoSpecboxForm>>(); //基本信息表单标记ref
const selectDomId = ref("");
interface SpecboxOrder {
  id: String /*主键*/;
  specimenId: String;/*标本ID */
  specboxId: String;/*标本盒表 */
  orderNumber: String;/*库位号 */
  empty: Number;/*存储状态 0为空，1为放置 */
  status: Number;/*状态 */
  deptName: String;/* */
  orderRow: String;/*行号 */
  orderColumn: String;/*列名称 */
}
// 库存表
interface SamstoSampleStorage {
  id: String /*主键*/;
  specimenId: String;/*标本ID */
  specimenType: String;/*标本类型 */
  workGroup: String;/*工作组 */
  operator: String;/*操作人 */
  fridgeId: String;/*所在冰箱 */
  layerId: String;/*所在层 */
  specboxId: String;/*标本盒表 */
  orderNumber: String;/*库位号 */
  location: String;/*仓库位置 */
  inspectionTime: String;/*检验时间 */
  inTime: String;/*入库时间 */
  expirationTime: String;/*存储到期时间 */
  status: Number;/*状态 */
  deptName: String;/*所属科室 */
}
// 绑定库存数据
let boxData= reactive({
  id: '',
  lData: [],
  wData:[],
  specboxOrders:[]
})
let specboxData: any = ref({
  stoPid:'',
  stoPidName:'',
  stoId:'',
  stoName:'',
  fridge:'',
  fridgeId:'',
  layer:'',
  layerId:'',
  specboxCode:''
});

defineExpose({
  initPage, selectSpecboxOrder
});
// 父组件传值
let props = defineProps({
  //  infoDicts: { type: Array as PropType<any>, required: true },
  curSelectRow: { type: Object as PropType<any>, required: true }
}) as any;

async function initPage(selsectRow: any) {
  //findList();
}
interface Cell {
  row: String;
  col: String;
  status: CellStatus;
  reqNo: String;
  specboxOrderId: String;
  stoPidName: String;
  stoName: String;
  fridge: String;
  layer: String;
}
// 初始状态
const cells = ref<Cell[]>([]);
type CellStatus = 'empty' | 'waitOccupied' | 'occupied' | 'unoccupied' | 'selected' | 'borrowed';

// 方法定义区 =============
onMounted(() => {

});

/**选择样本盒 */
function changeBoxOrder() {
  storagedisplayRef.value?.handleSearch();
  proxy.$nextTick(() => {
    dialogFormVisible.value = true;
  })
}
/**确认入库*/
function askBoxOrder(){
  if (specboxOrderList.length<=0){
    VxeMessage('没有要留样的孔位', VxeNotifyType.warning);
    return
  }
  //动态塞入样本盒id和仓位id
  for (const val of specboxOrderList) {
    for (const val1 of boxData.specboxOrders) {
      if (val.row+val.col==val1.orderNumber){
        val.specboxId=val1.specboxId;
        val.specboxOrderId=val1.id;
        val.storagePid=specboxData.stoPid
        val.storagePname=specboxData.stoPidName
        val.storageId=specboxData.stoId
        val.storageName=specboxData.stoName
        val.fridgeCode=specboxData.fridge
        val.fridgeId=specboxData.fridgeId
        val.layerId=specboxData.layerId
        val.specboxCode=specboxData.specboxCode
        val.layerCode=specboxData.layer
      }
    }
  }

  proxy
      .$confirm('确定入库？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(async () => {
        const url = '/api/samsto/specboxOrderReq/batchAddOrderReq';
        proxy.$http.post(url, specboxOrderList).then((res: any) => {
          if (res.status.code === 1) {
            setOccupied(specboxOrderList);
            //刷新申请信息
            proxy.$emit('refreshReq');
            specboxOrderList.length=0;
            VxeMessage('入库成功', VxeNotifyType.success);
          } else {
            VxeMessage(res.status.msg, VxeNotifyType.error);
          }
        });
      })
      .catch((err: any) => {
        // VxeMessage(err, VxeNotifyType.error);
      });
}
//设置成已占用
function setOccupied(specboxOrderList){
  for (const item of specboxOrderList) {
    const cell = cells.value.find(cell => cell.row === item.row && `${cell.col}` === `${item.col}`);
    cell.status = 'occupied';
  }
}
//选择样本盒
async function selectSpecboxOrder(selsectRows: any) {
  const selectedCells = cells.value.filter(cell => cell.status === 'unoccupied');
  if (selectedCells.length<=0){
    VxeMessage('请选择要留样的孔位', VxeNotifyType.warning);
    return
  }
  //更改状态
  // 提取 specboxOrderList 中的所有 reqNo
  const specboxReqNos = specboxOrderList.map(item => item.reqNo);

// 过滤 selsectRows，移除 specboxOrderList 中存在的 reqNo
  const filteredRows = selsectRows.filter(row => !specboxReqNos.includes(row.reqNo));
  if (selectedCells.length < filteredRows.length){
    VxeMessage('当前标本盒内孔位不足', VxeNotifyType.warning);
    return
  }
  filteredRows.forEach((item, index) => {
    let cell = selectedCells[index];
    cell.status = 'waitOccupied';
    cell.reqNo = item.reqNo;
    let specboxOrder = {
      specboxId: '',/*标本盒id */
      specboxOrderId: '',/*标本仓位id */
      enterTime: formatDateTime(new Date(), 'yyyy-MM-dd hh:mm:ss'),/*入仓时间 */
      destroyTime: formatDateTime(new Date().setTime(new Date().getTime() + 3600 * 1000 * 24 * 7), 'yyyy-MM-dd hh:mm:ss'),/*入仓时间 */
      reqNo: item.reqNo,/*条码号 */
      status: 5,/*状态 */
      row: cell.row,
      col: cell.col
    }
    specboxOrderList.push(specboxOrder);
  })
}

// 获取表格数据 00012311
async function findList() {
  drawer.value = false;
  // showLoading.value = true;
  showLoading.value = false;
  info.value = {};
  tableData.length = 0; //放入数据前清空数据
  const res: any = await samstoSpecboxFindInfoByCode(
    {
      keywords: form.keyvalue
    })
  if (res.status.code == 1) {
    info.value = res.data;
    let specboxArray = info.value.specboxArray.split('X');
    if (isEmpty(specboxArray)) {
      return;
    }
    if (isEmpty(info.value.orderNumber)) {
      return;
    }
    let orderNumber = eval("(" + info.value.orderNumber + ")");
    let specboxOrders = info.value.specboxOrders;
    if (specboxArray.length == 1) {
      tableHard.value.length = 0

      specboxOrders.forEach((item, index) => {
        //初始化表格数据
        if (isEmpty(tableData[item.orderRow])) {
          tableData[item.orderRow] = new Map<String, SpecboxOrder>(0);
          tableData[item.orderRow].setKey(index, item.orderColumn);
          tableData[item.orderRow].setValue(index, item);
        } else {
          tableData[item.orderRow].setKey(index, item.orderColumn);
          tableData[item.orderRow].setValue(index, item);
        }
        //写入列数据
        tableData[item.orderRow][item.orderColumn] = item;
        //写入仓位数组
        orderNumberArr[index] = {
          index: index,
          rowL: item.orderRow,
          columnW: item.orderColumn,
          orderNumber: item.orderNumber
        };
      });
      //初始化表头
      // if(!isEmpty(tableData[1])){
      //   for (let [key, value] of tableData[1]) {
      //       console.log(value,"tableHard item");
      //     tableHard.value[value.orderColumn]={title:"#",field:value.orderColumn};
      //   }
      // tableData[1].forEach((item,index)=>{
      //   console.log(item,"tableHard item");
      // });
      // }
      for (let [key, value] of tableData[1]) {
        console.log(value, "tableHard item");
        tableHard.value.push({ title: "#", field: value.orderColumn });
      }
    }
    if (specboxArray.length == 2) {
      let specboxNunArrayL = orderNumber.L.split(',');
      let specboxNunArrayW = orderNumber.W.split(',');
      //初始化表头和初始化表格数据
      specboxNunArrayL.unshift("#")
      tableHard.value.length = 0;
      for (let i = 1; i <= specboxNunArrayL.length; i++) {
        tableHard.value.push({ title: specboxNunArrayL[i], field: specboxNunArrayL[i] });
      }
      console.log(tableHard, "tableHard-specboxNunArrayL");
      specboxNunArrayW.forEach((item, index) => {
        tableData[index] = new Map<String, SpecboxOrder>(0);
      });
      console.log(tableData, "tableData-specboxNunArrayW");
      //写入列数据
      specboxOrders.forEach((item, index) => {
        tableData[item.orderRow].set("#", initBoxDoder(item.orderRow));
        tableData[item.orderRow].set(item.orderColumn, item);
        //[item.orderColumn]=item;
        //写入仓位数组
        orderNumberArr[index] = {
          index: index,
          rowL: item.orderRow,
          columnW: item.orderColumn,
          orderNumber: item.orderNumber
        };
      });
    }
  }
  console.log(tableData, "tableData");
  showLoading.value = false;
}
function initBoxDoder(orderRow) {
  return {
    createTime: "",
    creator: "",
    delFlag: 0,
    delTime: null,
    deptName: "",
    editTime: null,
    editor: null,
    empty: 0,
    id: "",
    orderColumn: "",
    orderNumber: "",
    orderRow: orderRow,
    orgId: "",
    specboxId: "",
    specimenId: null,
    status: 1
  };
}



// 表格选中当前行
function tableCellClick({ row }: any) {
  curSelectRow.value = row;
  proxy.$forceUpdate();
  selectItemRows(curSelectRow.value);
}
//选中行后传值给FORM
async function selectItemRows(row) {
  let selectItem = row;
  samstoSpecboxFormRef.value?.initPage(selectItem);
  proxy.$forceUpdate();
}

// 获取单元格状态
const getCellClass = (row: string, col: string) => {
  const cell = cells.value.find(cell => `${cell.row}` === `${row}` && `${cell.col}` === `${col}`);
  return cell ? cell.status : 'empty';
};
const getIsActived = (row: string, col: string) => {
  const cell = cells.value.find(cell => `${cell.row}` === `${row}` && `${cell.col}` === `${col}`);
  return cell && cell.isactived ? true : false;
};
// 点击选择状态
const selectCell = (row: String, col: String) => {
  cells.value.forEach((m) => {
    m.isactived = false;
  });
  const cell = cells.value.find(cell => cell.row === row && `${cell.col}` === `${col}`);
  proxy.$emit('selectReqNo', cell);
  if (cell) {
    switch (cell.status) {
      case 'empty':
        cell.status = 'unoccupied';
        cell.isactived = true;
        break;
      case 'unoccupied':
        cell.status = 'empty';
        break;
      case 'selected':
        cell.status = 'empty';
        break;
    }
  }

};

//获取选中的试剂盒
function changeBox(val: any){
  specboxData.stoPid=val.stoPid;
  specboxData.stoPidName=val.stoPidName;
  specboxData.stoId=val.stoId;
  specboxData.stoName=val.stoName;
  specboxData.fridge=val.fridge;
  specboxData.fridgeId=val.specboxData.fridgeId;
  specboxData.layerId=val.specboxData.layerId;
  specboxData.specboxCode=val.specboxData.specboxCode;
  specboxData.layer=val.layer;

  const orderData =val.orderData;
  boxData.lData.length=0;
  boxData.wData.length=0;
  boxData.specboxOrders.length=0;
  cells.value.length=0;
  boxData.lData.push(...orderData.orderColumns);
  boxData.wData.push(...orderData.orderRows);
  boxData.specboxOrders.push(...orderData.specboxOrders);
  for (let row = 0; row < boxData.lData.length; row++) {
    for (let col = 0; col < boxData.wData.length; col++) {
      //添加集合遍历
      const data ={
        row: boxData.lData[row],
        col: `${boxData.wData[col]}`,
        status: 'empty', // 初始状态为空位
        isactived: false,
        orderNumber:boxData.lData[row]+`${boxData.wData[col]}`
      }
      cells.value.push(data);
    }
  }
  //动态塞入样本盒id和仓位id
  for (const val of cells.value) {
    val.stoPidName=specboxData.stoPidName;
    val.stoName=specboxData.stoName;
    val.fridge=specboxData.fridge;
    val.layer=specboxData.layer;
    for (const val1 of boxData.specboxOrders) {
      if (val.row+val.col==val1.orderNumber &&  val1.empty == 1){
        val.status='occupied';
        val.reqNo=val1.reqNo;
        val.specboxOrderId=val1.id;
      }
    }
  }
  dialogFormVisible.value = true;
}
</script>
<style lang="scss" scoped>
#samstoSpecboxList {
  width: 100%;
  height: 100%;
  .bodyContent {
    // 面包屑40px  上下间距10px
    height: calc(100% - 60px);
    .hand-cursor {
      cursor: pointer; /* 鼠标指针在元素上时显示为手指形状 */
    }
    .area {
      background-color: $base-white;
      // 附加按钮间距
      .button-blue,
      .button-red {
        margin: 5px 0 5px 5px;
      }
      .select-active {
        border-color: chocolate;
        border-style: dotted;
      }
      .tableBox {
        height: calc(100% - 40px);
      }
      .el-tabs {
        border: none;
        height: 100%;
        :deep(.el-tabs__content) {
          padding: 0;
          height: calc(100% - 39px);
          .el-tab-pane {
            height: 100%;
          }
          #pane-0 {
            padding: 15px;
            height: calc(100% - 30px);
          }
        }
      }
    }
    .bankItemContent {
      min-height: 600px;
      border-radius: 10px;
    }

    .disabled {
      pointer-events: none;
      opacity: 0.5;
    }
  }
}

.sample-box {
  width: 100%;
  height: auto;
  padding: 10px;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}

.rack {
  display: flex;
  flex-direction: column;
  border: 2px solid #eee;
  border-radius: 5px;
}

.rack-row {
  display: flex;
  justify-content: center;
}

.rack-cell {
  width: 40px;
  height: 40px;
  margin: 3px;
  border-radius: 50%;
  background-color: #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.rack-cell.empty {
  background-color: #e0e0e0; /* 空位 */
}

.rack-cell.unoccupied {
  background-color: #32cd32; /* 未占用（绿色） */
}

.rack-cell.selected {
  background-color: #1e90ff; /* 选中（蓝色） */
}

.rack-cell.waitOccupied {
  background-color: #ff6347; /* 待占用（粉色） */

}

.rack-cell.occupied {
  background-color: #f80707; /* 已占用（红色） */
}


.rack-cell.borrowed {
  background-color: #ffeb3b; /* 借出（黄色） */
}
</style>

